package com.imooc.test;

import com.google.gson.Gson;
import com.imooc.pojo.Stu;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Base64;
import javax.crypto.SecretKey;

@SpringBootTest
public class JWTTestIgnore {

    public static final String USER_KEY="imooc12345678901234567890";

    @Test
    public void createToken() {


        String base64 = Base64.getEncoder().encodeToString(USER_KEY.getBytes());
        // 1. 对密钥进行base64编码
//        String base64=new BASE64Encoder().encode(USER_KEY.getBytes());

        // 2. 对base64生成一个密钥的对象
        SecretKey secretKey = Keys.hmacShaKeyFor(base64.getBytes());

        Stu stu=new Stu(101,"gqt",18);
        String json = new Gson().toJson(stu);


        // 3. 通过jwt去生成一个token字符串
         String myJWT= Jwts.builder()
                 .setSubject(json)    // 设置自定义数据
                 .signWith(secretKey)   // 使用哪个密钥对象
                 .compact();

         System.out.println(myJWT);
    }


    @Test
    public void checkToken() {
        String jwt="eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ7XCJpZFwiOjEwMSxcIm5hbWVcIjpcImdxdFwiLFwiYWdlXCI6MTh9In0.NFK4s-xfvuVMsQdn6THfeqWsYdAcky2fVyDd0bKNBM4";

        String base64 = Base64.getEncoder().encodeToString(USER_KEY.getBytes());

        SecretKey secretKey = Keys.hmacShaKeyFor(base64.getBytes());

        // 校验jwt
        JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(secretKey).build();

        // 解析通过可以获得claims ，如果抛出异常说明jwt不通过
        Jws<Claims> jws = jwtParser.parseClaimsJws(jwt);

        String subject = jws.getBody().getSubject();
        Stu stu=new Gson().fromJson(subject, Stu.class);
        System.out.println(stu);
    }
}
